package com.zq.learn.spark.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Collections;
import java.util.Properties;

/**
 * UserKafkaConsumer
 *
 * @author ZhangQi
 * @date 2020/2/10
 */
public class UserKafkaConsumer extends Thread {
  private String topic;

  public UserKafkaConsumer(String topic){
    this.topic=topic;
  }

  @Override
  public void run() {
    Properties p = new Properties();
    p.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    p.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    p.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    p.put(ConsumerConfig.GROUP_ID_CONFIG, "duanjt_test");

    KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<String, String>(p);
    kafkaConsumer.subscribe(Collections.singletonList(topic));// 订阅消息

    while (true) {
      ConsumerRecords<String, String> records = kafkaConsumer.poll(100);
      for (ConsumerRecord<String, String> record : records) {
        System.out.println(String.format("topic:%s,offset:%d,消息:%s", //
          record.topic(), record.offset(), record.value()));
      }
      try {
        sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
